<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
<!--      <el-form-item label="门店编号" prop="storeId">-->
<!--        <el-input v-model="formData.storeId" placeholder="请输入门店编号" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="订单类型" prop="orderType">-->
<!--        <el-radio-group v-model="formData.orderType">-->
<!--          <el-radio-->
<!--            v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_ORDER_TYPE)"-->
<!--            :key="dict.value"-->
<!--            :label="dict.value"-->
<!--          >-->
<!--            {{ dict.label }}-->
<!--          </el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
      <el-form-item label="车牌" prop="licensePlate">
        <el-input v-model="formData.licensePlate" placeholder="请输入车牌" />
      </el-form-item>
      <el-form-item label="手机号" prop="telephone">
        <el-input v-model="formData.telephone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="VIN" prop="vin">
<!--        <el-input v-model="formData.vin" placeholder="请输入VIN" />-->
        <el-input
          v-model="formData.vin"
          style="max-width: 600px"
          placeholder="请输入VIN"
          class="input-with-select"
        >
          <template #append>
            <el-button @click="handleJyCarTypeByVin" type="success">搜索车型</el-button>
          </template>
        </el-input>
      </el-form-item>


<!--      <el-form-item label="排序" prop="sort">-->
<!--        <el-input v-model="formData.sort" placeholder="请输入排序" />-->
<!--      </el-form-item>-->
      <el-form-item label="车型" prop="carType">
        <el-input v-model="formData.carType" placeholder="请输入车型" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
      </el-form-item>
      <el-form-item label="客户地址" prop="customerAddrress">
        <el-input v-model="formData.customerAddrress" placeholder="请输入客户地址信息" />
      </el-form-item>
      <el-form-item label="订单价格" prop="orderPrice">
        <el-input v-model="formData.orderPrice" placeholder="请输入订单价格" />
      </el-form-item>

      <el-form-item label="开启状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { OrderApi, OrderVO } from '@/api/dispatch/order'
import {ElLoading, ElMessage} from "element-plus";
import {SaleOrderApi} from "@/api/erp/sale/order";

/** 派单系统 订单 表单 */
defineOptions({ name: 'OrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  storeId: undefined,
  orderType: undefined,
  licensePlate: undefined,
  telephone: undefined,
  vin: undefined,
  remark: undefined,
  status: undefined,
  sort: 1,
  carType: undefined,
  customerName: undefined,
  customerAddrress: undefined,
  orderPrice: undefined,
})
const formRules = reactive({
  licensePlate: [{ required: true, message: '车牌不能为空', trigger: 'blur' }],
  telephone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  vin: [{ required: true, message: 'VIN不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  carType: [{ required: true, message: '车型不能为空', trigger: 'blur' }],
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  customerAddrress: [{ required: true, message: '客户地址信息不能为空', trigger: 'blur' }],
  orderPrice: [{ required: true, message: '订单价格不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

//根据vin获取车型
const handleJyCarTypeByVin = async () => {
  const vinVal = formData.value.vin;
  if (vinVal == undefined || vinVal.length != 17) {
    ElMessage.error('请输入正确的17位VIN');
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: '车型查询中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const data = await SaleOrderApi.getJyCarTypeByVin(vinVal);


  if (data == null) {
    formData.value.carType = undefined;
    formData.value.productType = undefined;
    formData.value.amVehicleId = undefined;
    formData.value.amMainBrandName = undefined;
    formData.value.amBrandName = undefined;
    formData.value.amSeriesName = undefined;
    formData.value.amSeriesId = undefined;
    formData.value.amVehicleName = undefined;
    ElMessage.error('未查询到车型信息,请检查VIN是否正确');
  } else {
    //车型
    formData.value.carType = data.amBrandName + data.amSeriesName + '-' + data.amYear + '款';
    //销售车型ID
    // formData.value.amVehicleId = data.amVehicleId;
    //
    // formData.value.amMainBrandName = data.amMainBrandName;
    // formData.value.amBrandName = data.amBrandName;
    // formData.value.amSeriesName = data.amSeriesName;
    // formData.value.amSeriesId = data.amSeriesId;
    // formData.value.amVehicleName = data.amVehicleName;
    // formData.value.amYear = data.amYear;
  }
  setTimeout(() => {
    loading.close()
  }, 500)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderApi.getOrder(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderVO
    if (formType.value === 'create') {
      await OrderApi.createOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderApi.updateOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    storeId: undefined,
    orderType: undefined,
    licensePlate: undefined,
    telephone: undefined,
    vin: undefined,
    remark: undefined,
    status: undefined,
    sort: 1,
    carType: undefined,
    customerName: undefined,
    customerAddrress: undefined,
    orderPrice: undefined,
  }
  formRef.value?.resetFields()
}
</script>
